<?php
require_once(Mage::getBaseDir('lib')."/K3/k3.class.php");
class Silk_Zgb_Adminhtml_InventoryController extends Mage_Adminhtml_Controller_Action
{
	protected function _initAction()
	{
		$this->loadLayout()->_setActiveMenu("catalog/inventory")->_addBreadcrumb(Mage::helper("adminhtml")->__("出入库管理"),Mage::helper("adminhtml")->__("出入库管理"));
		return $this;
	}
	public function indexAction() 
	{
	    $this->_title($this->__("轻松老板"));
	    $this->_title($this->__("出入库管理"));

		$this->_initAction();
		$this->renderLayout();
	}

	public function listGridAction()
	{
		$this->loadLayout()->renderLayout();
	}

	public function newGridAction()
	{
		$this->loadLayout()->renderLayout();
	}

	public function findAction()
	{
		$this->loadLayout()->renderLayout();
	}
	public function checkAction()
	{
		$sku = $this->getRequest()->getParam('sku');

        $productId = Mage::getModel('catalog/product')->getIdBySku($sku);

        $websiteId = Mage::helper("qslb")->_getwebsiteId();
        
        if(!$websiteId)
        {
            echo Zend_Json::encode(array('error'=>true,'message'=>'没有站点，请切换到当前站点操作!'));
            return;
        }
        
        if(!$productId)
        {
        	echo Zend_Json::encode(array('error'=>true,'message'=>'商品未找到!'));
        	return;
        }

        $product = Mage::getModel("catalog/product")->load($productId);

        $websiteIds = $product->getWebsiteIds(); 

        if(!in_array($websiteId, $websiteIds)){
            echo Zend_Json::encode(array('error'=>true,'message'=>'商品未找到!'));
            return;
        }

    	$url = $this->getUrl('admin_zgb/adminhtml_inventory/new', array('product_id'=>$productId,'website_id'=>$websiteId));
        
    	echo Zend_Json::encode(array('error'=>false,'message'=>'商品未找到!','url'=>$url));
        
  
	}

	public function newAction()
	{
		$this->loadLayout()->renderLayout();
	}

	public function updateAction()
	{
		//add by wanglin
		$add_websiteid = array(11,20,21,22,19);    //开通的站点ID
		$data 	   = array('error'=>true,'message'=>'');
    	$storeId   = $this->getRequest()->getParam('');
    	// if(!$storeId)
    	// {
    	// 	$data['message'] = "请先选择地区";
    	// 	echo Zend_Json::encode($data);
    	// 	return;
    	// }
    	$productId = $this->getRequest()->getParam('product_id');
    	$websiteId = $this->getRequest()->getParam('website_id');
        $storeId   = Mage::getModel('core/website')->load($websiteId)->getDefaultStore()->getId();
    	$qty 	   = intval($this->getRequest()->getParam('qty'));
    	if($qty<=0){
    		$data['message'] = "请输入数量";
    		echo Zend_Json::encode($data);
    		return;
    	}
    	$operation = $this->getRequest()->getParam('operation');
    	if($operation == 2){
            //出库
            $resource = Mage::getSingleton('core/resource');
            $db = $resource->getConnection('core_read');
            $sql = "select * from aitoc_cataloginventory_stock_item where product_id='{$productId}' and website_id='{$websiteId}'";
            $query = $db->fetchAll($sql);
            foreach ($query as $value){
                $result = $value["qty"];
            }
            if($qty>$result){
                $data["message"] = "出库数量大于库存";
                echo Zend_Json::encode($data);
                return;
            }
            $qty1 = -abs($qty); 		//传入后台的数量
            $FStockDirect = 'GENERAL';  //传到K3的退货标志
    	}elseif ($operation == 3){
    		//退货
    		$FStockDirect = 'RETURN';
    		$qty1 = abs($qty);
    	}else{
    		$FStockDirect = 'GENERAL';
    		$qty1 = abs($qty);
    	}
    	$nums 			= abs($qty);   //传入K3的数量
    	$FDEPTID 		= $this->getRequest()->getParam('FDEPTID');
    	$FACCEPTANCE 	= $this->getRequest()->getParam('FACCEPTANCE');
    	$FSUPPLIERID 	= $this->getRequest()->getParam('FSUPPLIERID');
    	$FQTRK_TYPE		= $this->getRequest()->getParam('FQTRK_TYPE');  	//其他入库用途
    	$FQTRK_TYPE_out	= $this->getRequest()->getParam('FQTRK_TYPE_out');  //其他出库用途
    	$comment 		= $this->getRequest()->getParam('comment');			//备注
    	$datetime 		= date('Y-m-d');
    	$webpost 		= new Webpost();
    	$product 		= Mage::getModel('catalog/product')->setStoreId($storeId)->load($productId);
    	$originQty 		= $product->getStockItem()->getQty();
    	$product_item_no =  $product->getItem_no();
    	if(in_array($websiteId, $add_websiteid)){
    		if($operation==1){ //入库
    			try {
    				$res = $webpost->add_STK_MISCELLANEOUS($FStockDirect,$comment,$websiteId,$FSUPPLIERID,$FACCEPTANCE,$FDEPTID,$FQTRK_TYPE,$product_item_no,$nums);
    			}catch(Exception $e){
    				$data["message"] = "k3保存失败";
    				echo Zend_Json::encode($data);
    				return;
    			}
    		}elseif ($operation==2 || $operation==3){  //出库
    			try {
    				$res  = $webpost->add_STK_MisDelivery($FStockDirect,$comment,$websiteId,$FSUPPLIERID,$FACCEPTANCE,$FDEPTID,$FQTRK_TYPE_out,$product_item_no,$nums);
    			}catch(Exception $e){
    				$data["message"] = "k3保存失败";
    				echo Zend_Json::encode($data);
    				return;
    			}
    		}
    		if(!empty($res)){
    			$session = Mage::getSingleton('admin/session');
    			$adminId = $session->getUser()->getId();
    			$date = date("Y-m-d H:i:s");
    			$resource = Mage::getSingleton('core/resource');
    			$db = $resource->getConnection('core_read');
    			$db->beginTransaction();
    			$sql = "insert into aitoc_inventory_stock(website_id,product_id,qty,operation,created_at,admin_id,comment)
    			values('{$websiteId}','{$productId}','{$qty1}','{$operation}','{$date}','{$adminId}','{$comment}')";
    			$db->exec($sql);
	    		try{
	    			$stockItem = Mage::getModel('cataloginventory/stock_item')->setStoreId($storeId)->loadByProduct($product);
	    			$originQty = $stockItem->getQty();
	    			if(!$originQty){
	    				$stockItemq = Mage::getModel('cataloginventory/stock_item');
	    				$stockItemq->setProductId($productId);
	    				$stockItemq->setWebsiteId($websiteId);
	    				$stockItemq->setStockId(1);
	    				$stockItemq->setQty(0);
	    				$stockItemq->save();
	    				$originQty =$stockItemq->getQty();
	    			}
		    	}catch(Exception $e){
	    			$db->rollback();
	    			//删除K3单据
	    			if($operation==1){
	    				$webpost->delete_STK_MISCELLANEOUS($res);
	    			}elseif($operation==3 || $operation==2){
	    				$webpost->delete_STK_MisDelivery($res);
	    			}
	    			$data["message"] = "更新后台库存失败，请初始化商品库存";
	    			echo Zend_Json::encode($data);
	    			return;
	    		}
    			$totalQty = $qty1 + $originQty;
    			if ($totalQty > 0) {
    				$sql = "update aitoc_cataloginventory_stock_item set qty='{$totalQty}',is_in_stock=1 where product_id='{$productId}' and website_id='{$websiteId}' and stock_id=1";
    			}else{
    				$sql = "update aitoc_cataloginventory_stock_item set qty='{$totalQty}',is_in_stock=0 where product_id='{$productId}' and website_id='{$websiteId}' and stock_id=1";
    			}
    			try{
    				$db->exec($sql);
    				$db->commit();
    				if($product && $product->getId()){
    					$stockItem = $product->getStockItem();
    					if($totalQty>0){
    						$stockItem->setIsInStock(1);
    					}else{
    						$stockItem->setIsInStock(0);
    					}
    				$stockItem->setQty($totalQty);
    				$stockItem->save();
    				}
    			}catch(Exception $e){
    				//删除K3单据
    				if($operation==1){
    					$webpost->delete_STK_MISCELLANEOUS($res);
    				}elseif($operation==3 || $operation==2){
    					$webpost->delete_STK_MisDelivery($res);
    				}
    				$data["message"] = "更新后台库存失败，请初始化商品库存";
    				echo Zend_Json::encode($data);
    				return;
    			}
    			$data["message"] = "成功";
    			echo Zend_Json::encode($data);
    			return;
    		}else{
    			$data["message"] = "K3保存失败";
    			echo Zend_Json::encode($data);
    			return;
    		}	
    	}else{
    		$session = Mage::getSingleton('admin/session');
    		$adminId = $session->getUser()->getId();
    		$date = date("Y-m-d H:i:s");
    		$resource = Mage::getSingleton('core/resource');
    		$db = $resource->getConnection('core_read');
    		$db->beginTransaction();
    		$sql = "insert into aitoc_inventory_stock(website_id,product_id,qty,operation,created_at,admin_id,comment)
    		values('{$websiteId}','{$productId}','{$qty1}','{$operation}','{$date}','{$adminId}','{$comment}')";
    		$db->exec($sql);
    		try{
    			$stockItem = Mage::getModel('cataloginventory/stock_item')->setStoreId($storeId)->loadByProduct($product);
    			$originQty = $stockItem->getQty();
    			if(!$originQty){
    				$stockItemq = Mage::getModel('cataloginventory/stock_item');
    				$stockItemq->setProductId($productId);
    				$stockItemq->setWebsiteId($websiteId);
    				$stockItemq->setStockId(1);
    				$stockItemq->setQty(0);
    				$stockItemq->save();
    				$originQty =$stockItemq->getQty();
    			}
    		}catch(Exception $e){
    			$db->rollback();
    			$data["message"] = "更新后台库存失败，请初始化商品库存";
    			echo Zend_Json::encode($data);
    			return;
    		}
    		$totalQty = $qty1 + $originQty;
    		if ($totalQty > 0) {
    			$sql = "update aitoc_cataloginventory_stock_item set qty='{$totalQty}',is_in_stock=1 where product_id='{$productId}' and website_id='{$websiteId}' and stock_id=1";
    		}else{
    			$sql = "update aitoc_cataloginventory_stock_item set qty='{$totalQty}',is_in_stock=0 where product_id='{$productId}' and website_id='{$websiteId}' and stock_id=1";
    		}
    		try{
    			$db->exec($sql);
    			$db->commit();
    			if($product && $product->getId()){
    				$stockItem = $product->getStockItem();
    				if($totalQty>0){
    					$stockItem->setIsInStock(1);
    				}else{
    					$stockItem->setIsInStock(0);
    				}
    				$stockItem->setQty($totalQty);
    				$stockItem->save();
    			}
    		}catch(Exception $e){
    			$data["message"] = "更新后台库存失败，请初始化商品库存";
    			echo Zend_Json::encode($data);
    			return;
    		}
    	}
	}

    public function notifyAction()
    {
        $this->_title($this->__("轻松老板"));
        $this->_title($this->__("库存预警"));

        $this->_initAction();
        $this->renderLayout();
    }

    public function notifyGridAction()
    {
        $this->loadLayout()->renderLayout();
    }

	protected function _isAllowed()
    {
    	return true;
        return Mage::getSingleton('admin/session')->isAllowed('newsletter/queue');
    }
}
